import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/quiz_room.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/playbill/central_stage/result_production.dart';

part 'answer_production.page.dart';

/// 答题页面
@PagePath('/answer')
class AnswerProduction extends StatefulWidget {
  const AnswerProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => _$AnswerProductionQuery().call();

  @override
  State<AnswerProduction> createState() => _AnswerProductionState();
}

class _AnswerProductionState extends State<AnswerProduction> {
  QuizRoom? _quizRoom;
  UserRoom? _userRoom;
  List<int> _userAnswers = []; // 用户选择的答案
  List<bool> _answerStates = []; // 每题的对错状态
  int _currentQuestionIndex = 0;

  @override
  void initState() {
    super.initState();
    _initializeAnswers();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_quizRoom == null) {
      _quizRoom = GlobalStateProvider.quizRoomOf(context);
      _userRoom = GlobalStateProvider.userRoomOf(context);
    }
  }

  /// 初始化答题状态
  void _initializeAnswers() {
    _userAnswers = List.filled(6, -1);
    _answerStates = List.filled(6, false);
  }

  /// 选择答案
  void _selectAnswer(int optionIndex) {
    if (_quizRoom == null) return;

    setState(() {
      _userAnswers[_currentQuestionIndex] = optionIndex;

      // 立即显示对错状态
      final currentQuestion =
          _quizRoom!.fetchAllQuestions()[_currentQuestionIndex];
      _answerStates[_currentQuestionIndex] =
          optionIndex == currentQuestion.correctAnswerIndex;
    });

    // 延迟后跳转到下一题或完成答题
    Future.delayed(Duration(milliseconds: 1500), () {
      if (mounted) {
        if (_currentQuestionIndex < 5) {
          setState(() {
            _currentQuestionIndex++;
          });
        } else {
          _finishQuiz();
        }
      }
    });
  }

  /// 完成答题
  void _finishQuiz() {
    if (_quizRoom == null || _userRoom == null) return;

    // 计算答对题目数量
    final correctCount = _answerStates.where((state) => state).length;

    // 提交答题结果
    final currentUser = _userRoom!.fetchCurrentUser();
    if (currentUser != null) {
      final attempt = _quizRoom!.submitQuizAnswers(
        userId: currentUser.id,
        userAnswers: _userAnswers,
      );

      // 延迟后跳转到结果页面
      Future.delayed(Duration(milliseconds: 500), () {
        if (mounted) {
          context.router.push(
            ResultProduction.query(
              correctCount: correctCount,
              totalCount: 6,
              passed: attempt.passed,
            ),
          );
        }
      });
    }
  }

  /// 构建标题栏
  Widget _buildHeader() {
    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.chevron_left_rounded, size: 36.w),
            ),
          ),
          Expanded(
            child: Center(
              child: Text('Lake Knowledge Quiz')
                  .fontSize(20.sp)
                  .textColor(Colors.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),
          36.w.widthBox,
        ],
      ),
    );
  }

  /// 构建题目内容
  Widget _buildQuestion() {
    if (_quizRoom == null) return SizedBox.shrink();

    final questions = _quizRoom!.fetchAllQuestions();
    final currentQuestion = questions[_currentQuestionIndex];

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 题目索引（带奖杯图标）
          Row(
            children: [
              16.w.widthBox,
              // 左边的奖杯装饰图标
              Image.asset(
                'assets/images/trophy.png',
                width: 48.w,
                height: 48.w,
              ),
              Spacer(),
              // 题目索引文字和装饰图片（使用Stack让装饰在文字下层）
              Stack(
                alignment: Alignment.center,
                children: [
                  // 装饰图片在下方（下层）
                  Image.asset(
                    'assets/images/index-bottom.png',
                    height: 6.h,
                    width: 73.w,
                    fit: BoxFit.fitWidth,
                  ),
                  // 题目索引文字在上方（上层）
                  Text('${_currentQuestionIndex + 1}/6')
                      .fontSize(32.sp)
                      .textColor(Colors.black)
                      .carterOne(weight: FontWeight.w400),
                ],
              ),
              16.w.widthBox,
            ],
          ),
          24.h.heightBox,
          // 题目内容
          Text(currentQuestion.question)
              .fontSize(20.sp)
              .textColor(ColorPalette.blue1)
              .carterOne(weight: FontWeight.w400),
          50.h.heightBox,
          Padding(
            padding: EdgeInsets.only(left: 16.w),
            child: Column(
              children: List.generate(currentQuestion.options.length, (index) {
                return _buildOptionCard(
                  index,
                  currentQuestion.options[index],
                  currentQuestion.correctAnswerIndex,
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建选项卡片
  Widget _buildOptionCard(int index, String optionText, int correctIndex) {
    Color borderColor = ColorPalette.blue1;

    if (_answerStates[_currentQuestionIndex]) {
      if (index == _userAnswers[_currentQuestionIndex]) {
        // 用户已选择且答对
        borderColor = Colors.green;
      }
    } else if (_userAnswers[_currentQuestionIndex] != -1) {
      // 已提交答案
      if (index == correctIndex) {
        // 正确答案
        borderColor = Colors.green;
      } else if (index == _userAnswers[_currentQuestionIndex]) {
        // 用户选错了
        borderColor = Colors.red;
      }
    }

    return Stack(
      clipBehavior: Clip.none,
      children: [
        // 第一个选项右上角的装饰图片
        if (index == 0)
          Positioned(
            top: -80.h,
            right: 0.w,
            child: Image.asset(
              'assets/images/answer-decoration.png',
              width: 125.w,
              fit: BoxFit.fitWidth,
            ),
          ),
        // 选项卡片
        Container(
          margin: EdgeInsets.only(bottom: 12.h),
          padding: EdgeInsets.only(
            left: 0.w,
            right: 6.w,
            top: 12.h,
            bottom: 12.h,
          ),
          decoration: BoxDecoration(
            color: ColorPalette.blue3,
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: borderColor, width: 2.w),
          ),
          child: Transform.translate(
            offset: Offset(-10.w, 0),
            child: Row(
              children: [
                // 选项字母
                Transform.rotate(
                  angle: -0.2,
                  child: Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(
                      color: ColorPalette.blue2,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Center(
                      child: Text(String.fromCharCode(65 + index)) // A, B, C, D
                          .fontSize(32.sp)
                          .textColor(ColorPalette.white)
                          .carterOne(weight: FontWeight.w400),
                    ),
                  ),
                ),
                12.w.widthBox,
                // 选项内容
                Expanded(
                  child: Text(optionText)
                      .fontSize(14.sp)
                      .textColor(ColorPalette.blue1)
                      .carterOne(weight: FontWeight.w400),
                ),
              ],
            ),
          ),
        ),
        // 选择答案后的右下角反馈盒子
        if (_userAnswers[_currentQuestionIndex] != -1 &&
            (index == _userAnswers[_currentQuestionIndex] ||
                index == correctIndex))
          Positioned(
            bottom: 12.h,
            right: 0.w,
            child: Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                color: index == correctIndex ? Colors.green : Colors.red,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  bottomRight: Radius.circular(16.r),
                ),
              ),
              child: Center(
                child: Image.asset(
                  index == correctIndex
                      ? 'assets/images/correct.png'
                      : 'assets/images/default.png',
                  width: 24.w,
                  height: 24.w,
                ),
              ),
            ),
          ),
      ],
    ).withTapEffect(
      onTap: () {
        _selectAnswer(index);
      },
    );
  }

  /// 构建说明文字
  Widget _buildInstructions() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 16.h),
      child: Text.rich(
        textAlign: TextAlign.center,
        TextSpan(
          children: [
            TextSpan(
              text: 'There are a total of ',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                fontFamily: 'Arimo',
                fontWeight: FontWeight.w400,
              ),
            ),
            TextSpan(
              text: '6',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                fontFamily: 'Arimo',
                fontWeight: FontWeight.w700,
                decoration: TextDecoration.underline,
                decorationColor: Colors.black,
              ),
            ),
            TextSpan(
              text: ' questions. If you answer ',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                fontFamily: 'Arimo',
                fontWeight: FontWeight.w400,
              ),
            ),
            TextSpan(
              text: '3',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                fontFamily: 'Arimo',
                fontWeight: FontWeight.w700,
                decoration: TextDecoration.underline,
                decorationColor: Colors.black,
              ),
            ),
            TextSpan(
              text:
                  ' questions correctly, you will receive a limited edition electronic seal (limited to once a month).',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                fontFamily: 'Arimo',
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                _buildHeader(),
                _buildQuestion(),
                _buildInstructions(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
